package com.lzx.iteam;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.ScheduleManagerAdapter;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.bean.ScheduleManager;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.ScheduleManagerMsg;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Megan on 16/3/14.
 */
public class ScheduleManagerActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private LinearLayout mLlBack, mLlHelp;
    private FrameLayout mLayoutMember;
    private ImageView mIvHelp, mIvNoData;
    private LinearLayout mLlNoData;
    private TextView mTvAddManager, mTvTitle, mTvNotice, mTvNoManager;
    private ListView mLvMangerList;

    private ScheduleManagerAdapter mAdapter;
    private CloudGroup mCloudGroup;
    private ArrayList<ScheduleManager> managers;
    private String delUserId;
    private String mGroupId;
    private int flag;  // 1:谁能看我的日程  2:审批管理 3：选择审批人 4：我能看谁的日程  5:周报查看人
    private final int GET_SCHEDULE_MANAGER = 1000;
    private final int DEL_SCHEDULE_MANAGER = 1001;
    public static int mSelectPosition = -1;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_SCHEDULE_MANAGER:
                    if (msg.arg1 == 0) {
                        managers = (ArrayList<ScheduleManager>) msg.obj;
                        if (managers.size() > 0) {
                            mLvMangerList.setVisibility(View.VISIBLE);
                            mLlNoData.setVisibility(View.GONE);
                            mAdapter.bindData(managers, flag);
                            mLvMangerList.setAdapter(mAdapter);
                        } else {
                            mLlNoData.setVisibility(View.VISIBLE);
                            mLvMangerList.setVisibility(View.GONE);
                            if (flag == 2 || flag == 3) {
                                mTvNoManager.setText("还没有审批人");
                                mTvNotice.setBackgroundResource(R.color.white);
                            } else if (flag == 4) {
                                mTvNoManager.setText("还没有共享日程成员");
                                mIvNoData.setImageResource(R.drawable.schedule_member_no_data);
                            }

                        }

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ScheduleManagerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ScheduleManagerActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case DEL_SCHEDULE_MANAGER:
                    if (msg.arg1 == 0) {
                        for (ScheduleManager manager : managers) {
                            if (manager.getUserId().equals(delUserId)) {
                                managers.remove(manager);
                                mAdapter.bindData(managers, flag);
                                if (managers.size() == 0) {
                                    mLlNoData.setVisibility(View.VISIBLE);
                                    mLvMangerList.setVisibility(View.GONE);
                                    if (flag != 1 && flag != 5) {
                                        mTvNoManager.setText("还没有审批人");
                                    }
                                }
                                break;
                            }
                        }

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ScheduleManagerActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ScheduleManagerActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_manager_layout);
        initViews();
        Intent pass = getIntent();
        String action = pass.getAction();
        if ("schedule_manager".equals(action)) {
            flag = 1;
            mTvTitle.setText("谁能看我的日程");
            getScheduleManager();
        } else if ("approval_leader_add".equals(action)) {
            flag = 2;
            mCloudGroup = (CloudGroup) pass.getSerializableExtra("groupData");
            mGroupId = mCloudGroup.groupId + "";
            mTvTitle.setText("审批人设置");
            mIvHelp.setVisibility(View.VISIBLE);
            getApprovalManager();
        } else if ("approval_leader_select".equals(action)) {
            flag = 3;
            mTvTitle.setText("审批人");
            mTvAddManager.setText("完成");
            mGroupId = pass.getStringExtra("group_id");
            mTvNotice.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mLayoutMember.getLayoutParams();
            linearParams.bottomMargin = Constants.dip2px(this, 50);
            mLayoutMember.setLayoutParams(linearParams);
            getApprovalManager();
        } else if ("schedule_member".equals(action)) {
            flag = 4;
            mTvAddManager.setVisibility(View.GONE);
            mTvTitle.setText("我能看谁的日程");
            getScheduleMember();

        } else if ("weekly_manager".equals(action)) {
            flag = 5;
            mTvTitle.setText("谁能看我的周报");
            mCloudGroup = (CloudGroup) pass.getSerializableExtra("group_data");
            mGroupId = mCloudGroup.groupId + "";
            mIvHelp.setVisibility(View.VISIBLE);
            getWeeklyManager();
        }

    }

    private void initViews() {
        mLlBack = (LinearLayout) this.findViewById(R.id.ll_schedule_manager_back);
        mLlNoData = (LinearLayout) this.findViewById(R.id.ll_schedule_manager_no_data);
        mLlHelp = (LinearLayout) this.findViewById(R.id.manager_ll_help);
        mIvHelp = (ImageView) this.findViewById(R.id.iv_schedule_manager_help);
        mTvAddManager = (TextView) this.findViewById(R.id.tv_schedule_manager_add);
        mLvMangerList = (ListView) this.findViewById(R.id.lv_schedule_manager_list);
        mTvTitle = (TextView) findViewById(R.id.manager_tv_title);
        mTvNotice = (TextView) findViewById(R.id.approval_manager_notice);
        mLayoutMember = (FrameLayout) findViewById(R.id.schedule_fl);
        mTvNoManager = (TextView) findViewById(R.id.tv_schedule_manager_no_data);
        mIvNoData = (ImageView) findViewById(R.id.iv_schedule_manager_no_data);

        mLlBack.setOnClickListener(this);
        mLlHelp.setOnClickListener(this);
        mTvAddManager.setOnClickListener(this);
        mAdapter = new ScheduleManagerAdapter(this);
        mLvMangerList.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_schedule_manager_back:
                finish();
                break;
            case R.id.manager_ll_help:
                if (flag == 2) {
                    Intent help = new Intent(ScheduleManagerActivity.this, WebViewActivity.class);
                    help.putExtra("title", "如何设置审批人?");
                    help.putExtra("type", 16);
                    startActivity(help);
                } else if (flag == 5) {
                    Intent help = new Intent(ScheduleManagerActivity.this, WebViewActivity.class);
                    help.putExtra("title", "如何设置周报阅览人?");
                    help.putExtra("type", 19);
                    startActivity(help);
                }
                break;
            case R.id.tv_schedule_manager_add:
                if (flag == 1) {
                    Intent intent = new Intent(ScheduleManagerActivity.this, ChooseContactByTeamActivity.class);
                    intent.setAction("schedule_manager_add");
                    startActivity(intent);
                } else if (flag == 2) {
                    Intent intent = new Intent(ScheduleManagerActivity.this, CloudDialerActivity.class);
                    intent.putExtra("group_id", mGroupId);
//                    intent.putExtra("tag_id", "0");
//                    intent.putExtra("tag_name", mCloudGroup.groupName);
                    intent.putExtra("group_name", mCloudGroup.groupName);
//                    intent.putExtra("group_type", mCloudGroup.groupType);
//                    intent.putExtra("user_type", mCloudGroup.userType);
                    intent.putExtra("contact_count", mCloudGroup.contactCount);
                    intent.putExtra("contact_id", mCloudGroup.contactId);
//                    intent.putExtra("groupData", mCloudGroup);
                    intent.putExtra("where", "cloud");
                    intent.setAction("approval_leader_add");
                    startActivity(intent);
                } else if (flag == 3) {
                    if (mSelectPosition != -1) {
                        Intent result = new Intent();
                        result.putExtra("leader", managers.get(mSelectPosition));
                        ScheduleManagerActivity.this.setResult(RESULT_OK, result);
                    }
                    finish();
                } else if (flag == 5) {
                    Intent intent = new Intent(ScheduleManagerActivity.this, CloudDialerActivity.class);
                    /*CloudDBOperation mCloudDBOperation = new CloudDBOperation(ScheduleManagerActivity.this);
                    mCloudGroup = mCloudDBOperation.getOneLocalGroupList(mGroupId);
                    CloudDialerActivity.selectedGroup = mCloudGroup;*/
                    intent.putExtra("group_id", mGroupId);
                    intent.putExtra("group_name", mCloudGroup.groupName);
                    intent.putExtra("contact_count", 10);
                    intent.putExtra("contact_id", mCloudGroup.contactId);
                    intent.putExtra("where", "cloud");
                    intent.setAction("weekly_manager_add");
                    startActivity(intent);
                }

                break;
        }
    }

    /**
     * 获取日程管理员
     */
    public void getScheduleManager() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        ScheduleManagerMsg scheduleManagerMsg = new ScheduleManagerMsg(mHandler.obtainMessage(GET_SCHEDULE_MANAGER), this);
        scheduleManagerMsg.mApi = AsynHttpClient.API_EVENT_CALENDAR_GET_MANAGERS;
        scheduleManagerMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(scheduleManagerMsg);

    }

    /**
     * 获取共享成员
     */
    public void getScheduleMember() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        ScheduleManagerMsg scheduleManagerMsg = new ScheduleManagerMsg(mHandler.obtainMessage(GET_SCHEDULE_MANAGER), this, 2);
        scheduleManagerMsg.mApi = AsynHttpClient.API_EVENT_CALENDAR_GET_CALENDAR_USER;
        scheduleManagerMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(scheduleManagerMsg);

    }

    /**
     * 获取周报查看人
     */
    public void getWeeklyManager() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        ScheduleManagerMsg scheduleManagerMsg = new ScheduleManagerMsg(mHandler.obtainMessage(GET_SCHEDULE_MANAGER), this);
        scheduleManagerMsg.mApi = AsynHttpClient.API_EVENT_WEEKLY_PERMISSION_USER_LIST;
        scheduleManagerMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(scheduleManagerMsg);

    }

    /**
     * 删除日程管理员
     */
    public void delScheduleManager(String userId, String approvalContactId) {
        delUserId = userId;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        if (flag == 1) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MANAGER, userId));
            GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(mHandler.obtainMessage(DEL_SCHEDULE_MANAGER));
            getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_CALENDAR_DEL_MANAGERS;
            getMsgHttpReceiver.mParams = nvps;
            AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);
        } else if (flag == 2) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_APPROVAL_CONTACT_ID, approvalContactId));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CURRENT_CONTACT_ID, mCloudGroup.contactId));
            GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(mHandler.obtainMessage(DEL_SCHEDULE_MANAGER));
            getMsgHttpReceiver.mApi = AsynHttpClient.KEY_APPROVAL_MAMAGER_REMOVE;
            getMsgHttpReceiver.mParams = nvps;
            AsynHttpClient.getInstance(this).execCcHttp(getMsgHttpReceiver);
        } else if (flag == 5) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEK_REVIEWER, userId));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
            GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(mHandler.obtainMessage(DEL_SCHEDULE_MANAGER));
            getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_WEEKLY_PERMISSION_USER_DEL;
            getMsgHttpReceiver.mParams = nvps;
            AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);
        }


    }

    /**
     * 获取审批管理员
     */
    public void getApprovalManager() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        /*if (flag == 3){
            nvps.add(new BasicNameValuePair("check_active", "1"));
        }*/
        ScheduleManagerMsg scheduleManagerMsg = new ScheduleManagerMsg(mHandler.obtainMessage(GET_SCHEDULE_MANAGER), this, 1);
        scheduleManagerMsg.mApi = AsynHttpClient.API_APPROVAL_MAMAGER_LIST;
        scheduleManagerMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(scheduleManagerMsg);

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        mLeader = managers.get(position);
        if (flag == 3 && !StringUtil.isEmpty(managers.get(position).getAttendance()) && "0".equals(managers.get(position).getAttendance())) {
            Toast.makeText(this, "不在一个考勤里面，不可选择", Toast.LENGTH_SHORT).show();
        } else if (flag == 4) {
            ScheduleManager member = managers.get(position);
            Intent intent = new Intent(this, ScheduleCalendarActivity.class);
            intent.putExtra("userId", member.getUserId());
            intent.putExtra("userName", member.getUserName());
            startActivity(intent);
        } else {
            mSelectPosition = position;
            mAdapter.notifyDataSetChanged();
        }

    }
}
